package cc.sheji.Service;


import cc.sheji.exception.FileException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.UUID;

@Service
public class FileService {

    @Value("${updataPath}")
    String updataPath;

    public ArrayList<String> subList=new ArrayList<>();
    {
        subList.add("jpg");
        subList.add("jpeg");
        subList.add("png");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    public String upload(MultipartFile file, HttpServletRequest req) throws FileException {
        System.out.println(updataPath);

        File folder = new File(updataPath);
        String format="";

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        System.out.println(oldName);
        String[] split = oldName.split("\\.");
        String subfix="jpg";
        if(split!=null&&split.length>0){
            subfix=split[split.length-1];
        }
        if(!(subList.indexOf(subfix)>=0)){
            subfix="jpg";
        }
        System.out.println("sub:"+subfix);
        String newName = UUID.randomUUID().toString() +"."+subfix;
        try {
            File file1 = new File(folder, newName);
            file.transferTo(file1);
            System.out.println(file1.getAbsoluteFile().toString());
            String   filePath = req.getScheme() + "://" + req.getServerName() + ":" +
                    req.getServerPort() + "/v1/image/" + format + newName;
            System.out.println("out:"+filePath);
            return filePath;
        } catch (IOException e) {
           throw new FileException();
        }
    }

}
